<?php

namespace app\api\controller\wxapp;

use addons\third\library\Service;
use addons\third\model\Third;
use app\common\library\Auth;
use fast\Http;
use think\Config;
use think\Cookie;
use think\Db;
use think\Session;
use think\Validate;
use app\common\controller\Api;
use think\Log;
use app\api\controller\Sms;
use app\api\model\Company;
use app\api\model\User as UserModel;

/**
 * 会员
 */
class User extends Api
{
    protected $noNeedLogin = '*';//['index', 'login'];

    protected $token = '';

    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }
    }

    public function is_regist_status()
    {
        $data = $this->request->param();
//        Log::error($data);
        $code = $data['code'];
        $userInfo = $data['rawData'];
//        Log::error($userInfo);
        if (!$data) {
            $this->error('参数错误');
        }
        $params = [
            'appid' => 'wx16e83bf32072d119',
            'secret' => '566e8c2e6b9c89cc55fcaa3221e30b81',
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        $json = (array)json_decode($result['msg'], true);
        if (isset($json['openid'])) {
            //Log::error(1);
            $third = Third::where(['openid' => $json['openid'], 'platform' => 'wxapp'])->find();//查询third表里面的openid
            //Log::error('third data:' . \GuzzleHttp\json_encode($third));
//            Log::error($third);
            //Log::error(2);
            if ($third == NULL || empty($result)) {
                //Log::error(3);
                $platform = 'wxapp';
                $result = [
                    'openid' => $json['openid'],
                    'userinfo' => [
                        'nickname' => $userInfo['nickname'],
                    ],
                    'access_token' => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in' => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'unionid' => !empty($json['unionid']) ? $json['unionid'] : '',
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickname'], 'avatar' => $userInfo['avatar']];
//                Log::error($extend);//到这里了是空的
                $ret = Service::connect($platform, $result, $extend);
                $data = ['userinfo' => $this->auth->getUserinfo(), 'token' => $this->auth->getToken()];
                //Log::error(\GuzzleHttp\json_encode($data));
                //$this->success(__('Logged in successful'), $data);

                UserModel::saveUidCache($data['userinfo']['user_id']);

                //返回union id
                $data['unionid'] = $result['unionid'];

                $this->error('你得去注册', $data);
            } else {
                //检测union id是否有值
                if ($third && !empty($json['unionid']) && empty($third['unionid'])) {
                    //更新用户的union id
                    Third::where(['id' => $third['id']])->update(['unionid' => $json['unionid']]);
                }

                //Log::error(4444444);
                $user = Db::name('user')->where('id', $third['user_id'])->find();

                //获取用户的企业信息[0:没注册企业端  1:已经注册企业端]
                $company = Company::findInfoByCondition(['user_id' => $third['user_id']]);
                $bossStatus = (int)$user['is_company_reg'];
                $requesting = $company ? (int)$company['requesting'] : 0;
                if ($bossStatus == 0) {
                    $requesting = 0;
                }

//                Log::error(4);
                if ($user['status'] != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($third['user_id']);

                $data = ['userinfo' => $this->auth->getUserinfo(), 'token' => $this->auth->getToken(), 'boss_status' => $bossStatus, 'requesting' => $requesting];
                //Log::error(\GuzzleHttp\json_encode($data));

                //返回union id
                $data['unionid'] = !empty($json['unionid']) ? $json['unionid'] : '';

                if (empty($user['mobile'])) {
                    //$token= Db::name('user_token')->where('user_id', $third['user_id'])->field('token')->find();
                    $this->error(__('去完善资料'),$data);
                }

                UserModel::saveUidCache($data['userinfo']['user_id']);

                if ($data['userinfo']['is_expert_reg'] == 0 && $data['userinfo']['is_company_reg'] == 0) {
                    //提醒去注册
                    $this->error('你得去注册', $data);
                } else {
                    $this->success(__('Logged in successful'), $data);
                }
            }
        } else {
//            Log::error(5);
            $this->error();
        }
    }


    /**
     * 登录
     */
    public function login()
    {
        $data = $this->request->param();
        $code = $data['code'];
        $userInfo = $data['rawData'];
//        Log::error($userInfo);
        if (!$data) {
            $this->error('参数错误');
        }
        $params = [
            'appid' => 'wx16e83bf32072d119',
            'secret' => '566e8c2e6b9c89cc55fcaa3221e30b81',
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
//        Log::error($result);
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
//            Log::error($json);
            if (isset($json['openid'])) {
//                Log::error($json['openid']);
                //如果有传Token
                if ($this->token) {
                    $this->auth->init($this->token);
                    //检测是否登录
                    if ($this->auth->isLogin()) {
                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wxapp'])->find();
//                        Log::error($third);
                        if ($third && $third['user_id'] == $this->auth->id) {
                            UserModel::saveUidCache($third['user_id']);
                            $this->success("登录成功", ['userInfo' => $this->auth->getUserinfo()]);
                        }
                    }
                }

                $platform = 'wxapp';
                $result = [
                    'openid' => $json['openid'],
                    'userinfo' => [
                        'nickname' => $userInfo['nickname'],
                    ],
                    'access_token' => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in' => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickname'], 'avatar' => $userInfo['avatar']];
//                Log::error($extend);//到这里了是空的
                $ret = Service::connect($platform, $result, $extend);
//                Log::error($ret);
                if ($ret) {
                    $auth = Auth::instance();

                    $userData = $auth->getUserinfo();
                    UserModel::saveUidCache($userData['user_id']);
//                    Log::error($auth);
                    $this->success("用户数据创建成功,请继续完善资料", ['userInfo' => $auth->getUserinfo()]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败");
            }
        }

        return;
    }

    /**
     * 绑定账号
     */
    public function bind()
    {
        $account = $this->request->post("account");
        $password = $this->request->post("password");
        if (!$account || !$password) {
            $this->error("参数不正确");
        }

        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $rule = [
            'account' => 'require|length:3,50',
            'password' => 'require|length:6,30',
        ];

        $msg = [
            'account.require' => 'Account can not be empty',
            'account.length' => 'Account must be 3 to 50 characters',
            'password.require' => 'Password can not be empty',
            'password.length' => 'Password must be 6 to 30 characters',
        ];
        $data = [
            'account' => $account,
            'password' => $password,
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error(__($validate->getError()));
            return false;
        }
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user = \app\common\model\User::get([$field => $account]);
        if (!$user) {
            $this->error('账号未找到');
        }
        $third = Third::where(['user_id' => $user->id, 'platform' => 'wxapp'])->find();
        if ($third) {
            $this->error('账号已经绑定其他小程序账号');
        }

        $third = Third::where(['user_id' => $this->auth->id, 'platform' => 'wxapp'])->find();
        if (!$third) {
            $this->error('未找到登录信息');
        }

        if ($this->auth->login($account, $password)) {
            $third->user_id = $this->auth->id;
            $third->save();
            $this->success("绑定成功", ['userInfo' => $this->auth->getUserinfo()]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 个人资料
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar');
        if (!$username || !$nickname) {
            $this->error("用户名和昵称不能为空");
        }
        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists) {
            $this->error(__('Username already exists'));
        }
        $avatar = str_replace(Config::get('upload.cdnurl'), '', $avatar);
        $user->username = $username;
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success('', ['userInfo' => $this->auth->getUserinfo()]);
    }

    /**
     * 保存头像
     */
    public function avatar()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->request('avatar');
        if (!$avatar) {
            $this->error("头像不能为空");
        }
        $avatar = str_replace(Config::get('upload.cdnurl'), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('', ['userInfo' => $this->auth->getUserInfo()]);
    }
}
